/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: Image_Dummy.cpp,v 1.19 2009-05-13 07:18:21 amaula Exp $
 *
 * \file
 * \brief Example module for the Image interface.
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "binbag.h"
#include "ImageServer.hpp"
#include "ImageContainer.hpp"
#include <sys/stat.h>
#include <string>
#include "JPEGDecoder.hpp"

//*****************************************************************************
// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Choose your namespace
using namespace MaCI;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************
// Own.
std::string imageFile; ///< Image file name. If zero.
int testimagemode = 1; // 0 for white noise, 1 for kuvaton :)
static std::string macigroup = "Dummy";
static std::string groupinstance = "Dummy";
//*****************************************************************************
static int gridImageWidth=10;
static int gridImageHeight=10;
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(3,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(3,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tAlarm_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  fprintf(stderr,"  [-I name]\t\t\tSpecify the MaCIGroup Interface Instance\n");
  fprintf(stderr,"  [-m mode]\t\t\tSpecify testimagemode. Currently supported; 0=whitenoise, 1=Kuvaton :)\n\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static unsigned int GenerateRGBWhiteNoise(unsigned char *buffer, const unsigned int buffersize,
                                          const unsigned int w, const unsigned int h)
{
  const unsigned int bcount = w * h * 3;

  assert(bcount <= buffersize);

  for (unsigned int i=0; i < buffersize && i < bcount; i += 3) {
    memset(buffer+i, random() % 255, 3);
  }

  return bcount;
} 
//*****************************************************************************

static void CreateTestImage_Kuvaton(Image::CImageContainer &img) 
{
  /* Note that this code is *hit. It was quickly hacked together to demonstrate
   * how easy it was. It took about 20 minutes to implement in full =P
   */
  using namespace MaCI::Image;
  static char buffer[4096 * 1000];
  struct stat f;
  int b;

 rikki_meni_yrita_uudestaan:
  system("wget -O imagedummy.tmp.html http://kuvaton.com/1/rand >&/dev/null");

  assert(stat("./imagedummy.tmp.html",&f) == 0);
  
  FILE *foo = fopen("./imagedummy.tmp.html", "rb");
  assert(foo != NULL);
  b = fread(buffer, f.st_size, 1, foo);
  fclose(foo);

  assert(b == 1);

  char name[256];
  char *ptr = strstr(buffer, "<img src=\"http://kuvaton.com/kuvei");
  assert(ptr != NULL);
  ptr += 10;
  int i = 0;
  do {
    name[i] = *ptr;
    if (name[i] == '\"') { name[i] = 0; break; }
    i++;
    ptr++;
  } while(1);
  
  std::string addr = std::string(name);

  dPrint(2,"Fetching image: '%s'", addr.c_str());

  if (strstr(addr.c_str(), ".jpg") != NULL || strstr(addr.c_str(), ".jpeg") != NULL) {
    
    char command[256];
    sprintf(command,"wget --header='Host: kuvaton.com' --header='User-Agent: Mozilla/5.0' "
            "--header='Referer: http://kuvaton.com/1/rand/' -O tmpimage.img %s >&/dev/null", 
            addr.c_str());
    //dPrint(1,"Executing: '%s'", command);
    system(command);
    
    
    if (stat("./tmpimage.img",&f) == 0) {
    
      foo = fopen("./tmpimage.img", "rb");
      assert(foo != NULL);
      b = fread(buffer, f.st_size, 1, foo);
      fclose(foo);
     
      if (b == 1) {
        
        // Only using Decoder for determining the image size.
        CJPEGDecoder d(buffer, f.st_size);
        const int w = d.GetImageWidth();
        const int h = d.GetImageHeight();
        
        dPrint(2,"Got image. Image is '%d x %d'. Broadcasting via MaCI::Image...", w, h);
        // Add to container.
        img.SetImageData((const unsigned char *)buffer, 
                         f.st_size, 
                         KImageDataJPEG,
                         w, h, 
                         KImageDataUnknown,
                         true); // COPY!
      } else {
        goto rikki_meni_yrita_uudestaan;
      }
    } else {
      goto rikki_meni_yrita_uudestaan;
    }
   
  } else {
    dPrint(1,"Unqualified! (Was not .jpg)");
    goto rikki_meni_yrita_uudestaan;
  }
}
//*****************************************************************************

static void CreateTestImage_Grid(Image::CImageContainer &img) 
{
  using namespace MaCI::Image;
  unsigned char sbuffer[gridImageWidth*gridImageHeight*3];
  
  memset(sbuffer,255,gridImageWidth*gridImageHeight*3);
  
  //horiz line
  memset(sbuffer+gridImageHeight/2*gridImageWidth*3, 0, gridImageWidth*3);
  
  //vert line
  for (int y=0;y<gridImageHeight;y++)
  {
    sbuffer[(gridImageWidth*y+gridImageWidth/2)*3]=0;
    sbuffer[(gridImageWidth*y+gridImageWidth/2)*3+1]=0;
    sbuffer[(gridImageWidth*y+gridImageWidth/2)*3+2]=0;
  }
  
  // Add to container.
  img.SetImageData(sbuffer, 
                   gridImageWidth*gridImageHeight*3, 
                   KImageDataRGB,
                   gridImageWidth, gridImageHeight, 
                   KImageDataUnknown,
                   true); // COPY!
  
  //increase size
  gridImageWidth++;
  gridImageHeight++;
}

//*****************************************************************************

static void CreateTestImage(Image::CImageContainer &img) 
{
  using namespace MaCI::Image;
  unsigned char sbuffer[4096*10];
  const unsigned int w = 100, h = 100;
  unsigned int used;

  // Generate noise
  used = GenerateRGBWhiteNoise(sbuffer, sizeof(sbuffer), w, h);
  
  // Add to container.
  img.SetImageData(sbuffer, 
                   used, 
                   KImageDataRGB,
                   w, h, 
                   KImageDataUnknown,
                   true); // COPY!
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  using namespace MaCI::Image;
  unsigned int interval = 1000;
  unsigned int seq = 0;
  EMaCIError e;
  bool r;
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);
  CImageServer is(&mcs, 0, "(RGB) DummyImages", "Image_Dummy");
  CImageData id;
  CImageContainer idc;

  // Set GroupName for MaCICtrlServer and Instance for ImageServer.
  mcs.SetGroupName(macigroup);
  is.SetInterfaceInstanceName(groupinstance);

  // Init random()
  srandom(time(NULL));

  switch(testimagemode) { 
  case 0:
    is.SetSourceInfo(TSourceInfo(0,
                                 "WhiteNoiseGenerator",
                                 "This is a WhiteNoiseGenerator for testing Image Interface (Image_Dummy)"));
    interval = 200;
    break;
  case 1:
    is.SetSourceInfo(TSourceInfo(0,
                                 "Kuvaton",
                                 "This imagesource fetches random images from Kuvaton.com (Interval 10s, be patient)"));
    interval = 10000;
    break;
  case 2:
    is.SetSourceInfo(TSourceInfo(0,
                                 "Grid",
                                 "This imagesource produces every 3 seconds a picture with straight horizontal and vertical lines. "
                                 "Picture width and height increase by 1 on every image"));
    interval = 3000;
    break;

  default:
    dPrint(1,"Invalid testimagemode %d!", testimagemode);
    abort();
    break;
  }

  // Create backend.
  id.CreateInternalBinBag();

  // Open.
  if (is.Open() == KMaCIOK) {
    
    // Run!
    while(run) {

      const int subscribers = is.GetInterfaceSubscriberCount();
      if (subscribers > 0) {
        // Create Img.
        switch(testimagemode) {
        case 0:
          CreateTestImage(idc);
          break;
        case 1:
          CreateTestImage_Kuvaton(idc);
          break;
        case 2:
          CreateTestImage_Grid(idc);
          break;
          
        }
        
        // Pack & send
        id.Reset();
        r = id.SetTimestamp(Common::TTimestamp()); // Set time to current.
        r &= id.AddImage(0, idc);
        assert(r == true);
        e = is.SendImageData(id);
        assert(e == KMaCIOK);
        
        // Print.
        ++seq;
        dPrint(1,"%u%s ImageData sent, (%ux%u, %u bytes), have %u subscribers currently", 
               seq,
               (seq%10==1&&seq%100-seq%10!=10) ? "st" : 
               (seq%10==2&&seq%100-seq%10!=10) ? "nd" :
               (seq%10==3&&seq%100-seq%10!=10) ? "rd" : "th",
               idc.GetImageInfoRef().imagewidth,
               idc.GetImageInfoRef().imageheight,
               idc.GetImageDataSize(),
               subscribers);
      
      } else {
        static unsigned int wbegin = 0;
        if (ownTime_get_ms_since(wbegin) > 5000) {
          dPrint(1,"Waiting for subscribers...");
          wbegin = ownTime_get_ms();
        }

      }

      // Sleep.
      if (interval) ownSleep_ms(interval);

    }

  } else {
    dPrint(1,"Failed to Open() ImageServer Interface! Fatal error! Exit!");

  }
   
  return 0;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 50002;
  std::string gimnetName;

  // Configuration parameters
  std::string configurationFile;
  std::string configurationBasekey;

  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(1);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.19 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "n:u:p:G:I:m:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////
    case 'm':
      testimagemode = atoi(optarg);
      dPrint(1,"Using testimagemode %d", testimagemode);
      break;

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(3,"Using MaCI-Group '%s'", optarg);
      break;

    case 'I':
      groupinstance = optarg;
      dPrint(3,"Using MaCI-Group Interface Instance '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.18  2008-12-18 08:18:48  amaula
 * Added note about subscribers count
 *
 * Revision 1.17  2008-12-18 08:00:21  amaula
 * More little features added.
 *
 * Revision 1.16  2008-12-18 07:44:08  amaula
 * Added handler for some error states.
 *
 * Revision 1.15  2008-12-17 09:47:19  aiholtta
 * Added new test mode: square picture with crossing lines and gradually
 * increasing size.
 *
 * Revision 1.14  2008-11-07 11:12:46  amaula
 * Lots of misc. changes.
 *
 * Revision 1.13  2008-11-04 12:01:24  amaula
 * Sleep moved.
 *
 * Revision 1.12  2008-11-04 10:28:33  amaula
 * Debugs cleaned up
 *
 * Revision 1.11  2008-11-04 10:17:50  amaula
 * Now also .jpeg files are accepted as jpg:s. Added also image size detection using the CJPEGDecoder class.
 *
 * Revision 1.10  2008-11-04 09:48:24  amaula
 * Kuvaton support fixed.
 *
 * Revision 1.9  2008-11-03 13:47:37  amaula
 * Kuvaton broke my Kuvaton viewer :( Still broken.
 *
 * Revision 1.8  2008-09-03 10:53:10  amaula
 * Added support for MaCISL
 *
 * Revision 1.7  2008-08-28 10:37:30  amaula
 * Implemented proper source handling support for Dummy and V4L2 module.
 *
 * Revision 1.6  2008-08-15 11:49:41  amaula
 * Removed external compression options - doesn't look very useful. Can be coded in the conversion field easily.
 *
 * Revision 1.5  2008-08-15 10:25:10  amaula
 * Almost complete.
 *
 * Revision 1.4  2008-08-14 10:47:07  amaula
 * Basic structure of Image interface enhanced. Will now start building converters.
 *
 * Revision 1.3  2008-08-13 08:54:48  amaula
 * Minor changes.
 *
 * Revision 1.2  2008-08-12 13:02:22  amaula
 * Dummy updated
 *
 * Revision 1.1  2008-08-12 06:57:11  amaula
 * Initial Imagestuff
 *
 * Revision 1.7  2008-06-27 10:07:10  amaula
 * Module updated.
 *
 * Revision 1.6  2008-06-13 10:24:19  amaula
 * Removed Basekey, added MaCIGroup (-G)
 *
 * Revision 1.5  2008-03-30 01:31:03  amaula
 * All MaCI stuff fixed to be GIMI 2.0.0 compliant.
 *
 * Revision 1.4  2008-03-25 09:53:16  amaula
 * Log entry added.
 *
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


